import { View, Text, Input, Button } from '@tarojs/components'
import { useState } from 'react'
import Taro, { useLoad } from '@tarojs/taro'
import './index.less'

export default function Login() {
  const [phone, setPhone] = useState('')
  const [code, setCode] = useState('')
  const [loading, setLoading] = useState(false)
  const [countdown, setCountdown] = useState(0)

  // 测试账户数据
  const testAccounts = [
    {
      phone: '13800138000',
      name: '张三',
      type: '黄金会员',
      isMember: true,
      memberLevel: '黄金会员',
      memberExpireDate: '2025-12-31'
    },
    {
      phone: '13900139000',
      name: '李四',
      type: '普通用户',
      isMember: false
    },
    {
      phone: '13700137000',
      name: '王五',
      type: '钻石会员',
      isMember: true,
      memberLevel: '钻石会员',
      memberExpireDate: '2025-12-31'
    }
  ]

  useLoad(() => {
    // 检查是否已登录
    try {
      const userInfo = Taro.getStorageSync('userInfo')
      if (userInfo) {
        Taro.switchTab({ url: '/pages/index/index' })
      }
    } catch (error) {
      console.log('检查登录状态失败')
    }
  })

  const handleSendCode = () => {
    if (!phone) {
      Taro.showToast({
        title: '请输入手机号',
        icon: 'none'
      })
      return
    }

    if (!/^1[3-9]\d{9}$/.test(phone)) {
      Taro.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      })
      return
    }

    // 模拟发送验证码
    setCountdown(60)
    const timer = setInterval(() => {
      setCountdown(prev => {
        if (prev <= 1) {
          clearInterval(timer)
          return 0
        }
        return prev - 1
      })
    }, 1000)

    Taro.showToast({
      title: '验证码已发送',
      icon: 'success'
    })
  }

  const createSampleOrders = (userPhone) => {
    const sampleOrders = [
      {
        id: `JJ${Date.now()}001`,
        type: 'pickup',
        serviceType: 'wash',
        clothesCount: 5,
        price: 75,
        address: '北京市朝阳区三里屯SOHO',
        contactName: '张先生',
        contactPhone: userPhone,
        createTime: '2025-01-20 14:30',
        appointmentTime: '2025-01-21 09:00',
        status: 'completed',
        pickupCode: '123456',
        payTime: '2025-01-20 14:35'
      },
      {
        id: `JJ${Date.now()}002`,
        type: 'store',
        serviceType: 'dry-clean',
        clothesCount: 3,
        price: 75,
        address: '捷净洗护(三里屯店)',
        contactName: '李女士',
        contactPhone: userPhone,
        createTime: '2025-01-22 10:15',
        appointmentTime: '2025-01-23 15:00',
        status: 'washing',
        pickupCode: '789012',
        payTime: '2025-01-22 10:20'
      },
      {
        id: `JJ${Date.now()}003`,
        type: 'pickup',
        serviceType: 'repair',
        clothesCount: 2,
        price: 60,
        address: '北京市海淀区中关村大街',
        contactName: '王先生',
        contactPhone: userPhone,
        createTime: '2025-01-25 16:45',
        appointmentTime: '2025-01-26 10:00',
        status: 'pending',
        pickupCode: '345678'
      }
    ]
    
    Taro.setStorageSync('orders', sampleOrders)
  }

  const handleLogin = async () => {
    if (!phone) {
      Taro.showToast({
        title: '请输入手机号',
        icon: 'none'
      })
      return
    }
    
    if (!code) {
      Taro.showToast({
        title: '请输入验证码',
        icon: 'none'
      })
      return
    }

    if (!/^1[3-9]\d{9}$/.test(phone)) {
      Taro.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      })
      return
    }

    if (code !== '123456') {
      Taro.showToast({
        title: '验证码错误',
        icon: 'none'
      })
      return
    }

    setLoading(true)
    
    try {
      // 模拟登录请求
      await new Promise(resolve => setTimeout(resolve, 1500))
      
      // 查找测试账户
      const testAccount = testAccounts.find(account => account.phone === phone)
      
      // 创建用户信息
      const userInfo = testAccount ? {
        phone: testAccount.phone,
        nickname: testAccount.name,
        avatar: 'https://img.yzcdn.cn/vant/cat.jpeg',
        isMember: testAccount.isMember,
        memberLevel: testAccount.memberLevel || '',
        memberExpireDate: testAccount.memberExpireDate || '',
        loginTime: new Date().toLocaleString()
      } : {
        phone: phone,
        nickname: `用户${phone.slice(-4)}`,
        avatar: 'https://img.yzcdn.cn/vant/cat.jpeg',
        isMember: false,
        loginTime: new Date().toLocaleString()
      }
      
      // 保存用户信息
      Taro.setStorageSync('userInfo', userInfo)
      
      // 为测试账户创建示例订单
      if (testAccount) {
        createSampleOrders(phone)
      }
      
      Taro.showToast({
        title: '登录成功',
        icon: 'success'
      })
      
      setTimeout(() => {
        Taro.switchTab({ url: '/pages/index/index' })
      }, 1000)
      
    } catch (error) {
      Taro.showToast({
        title: '登录失败，请重试',
        icon: 'none'
      })
    } finally {
      setLoading(false)
    }
  }

  const handleTestAccount = (account) => {
    setPhone(account.phone)
    setCode('123456')
    Taro.showToast({
      title: '已自动填入登录信息',
      icon: 'success'
    })
  }

  return (
    <View className='login-page'>
      {/* 头部Logo */}
      <View className='login-header'>
        <View className='login-logo'>
          <Text className='logo-icon'>🧺</Text>
          <Text className='logo-text'>捷净洗护</Text>
          <Text className='logo-subtitle'>专业洗护，贴心服务</Text>
        </View>
      </View>

      {/* 登录表单 */}
      <View className='login-form'>
        <View className='form-card'>
          <View className='form-title'>
            <Text className='title-text'>手机号登录</Text>
            <Text className='title-subtitle'>输入手机号获取验证码</Text>
          </View>

          <View className='form-item'>
            <Input
              type='number'
              placeholder='请输入手机号'
              value={phone}
              onInput={(e) => setPhone(e.detail.value)}
              maxlength={11}
            />
          </View>

          <View className='form-item code-item'>
            <View className='code-input'>
              <Input
                type='number'
                placeholder='请输入验证码'
                value={code}
                onInput={(e) => setCode(e.detail.value)}
                maxlength={6}
              />
            </View>
            <Button
              size='mini'
              type='default'
              disabled={countdown > 0}
              onClick={handleSendCode}
              className='code-btn'
            >
              {countdown > 0 ? `${countdown}s` : '获取验证码'}
            </Button>
          </View>

          <Button
            type='primary'
            loading={loading}
            onClick={handleLogin}
            className='login-btn'
          >
            {loading ? '登录中...' : '立即登录'}
          </Button>

          <View className='login-tips'>
            <Text className='tips-text'>
              登录即表示同意《用户协议》和《隐私政策》
            </Text>
          </View>
        </View>
      </View>

      {/* 测试账户 */}
      <View className='test-accounts'>
        <Text style={{ fontSize: '16px', fontWeight: 'bold', color: '#323233', marginBottom: '15px', display: 'block' }}>
          测试账户 (点击快速登录)
        </Text>
        
        {testAccounts.map((account, index) => (
          <View 
            key={index}
            className='account-item'
            onClick={() => handleTestAccount(account)}
          >
            <View className='account-info'>
              <Text className='account-name'>{account.name}</Text>
              <Text className='account-phone'>{account.phone}</Text>
            </View>
            <View className='member-badge'>
              <Text style={{ color: 'white', fontSize: '12px' }}>{account.type}</Text>
            </View>
          </View>
        ))}

        <View className='test-tips'>
          <Text className='tips-icon'>💡</Text>
          <View className='tips-content'>
            <Text>
              点击上方测试账户可快速登录体验，验证码统一为 123456。
              测试账户会自动创建示例订单数据，方便功能演示。
            </Text>
          </View>
        </View>
      </View>
    </View>
  )
}